<template>
	<!-- 课程目录 -->
	<div class="qy-com-course-lesson">
		<div v-for="(item) in list" :key="item.id" class="qy-tree-node">
			<div class="qy-tree-node-content" :class="[
          isChapter(item.type) ? 'qy-tree-node_parent' : '',
          activeNode(item.chapterId) ? 'is_current' : ''
        ]" @click="nodeClick(item)">
				<div class="content-top">
					<i class="playing"></i>
					<i class="index-name">{{ item.chapterIndexName }}</i>
					<i class="content-name ellipsis">
						<span
							v-if="isLesson(item.type)">{{ "「" + getCurrentLesson(item.contentType).name + "」" }}</span>{{
              item.name
            }}
					</i>
				</div>
				<div class="content-bottom" v-if="isLesson(item.type)">
					<div class="flex-wrap flex-column">
						<i class="default-desc" v-if="!isExamLesson(item.contentType)">{{
                  `需用时：${
                      item.passSecond == 0 ? "学习即完成  " : getTime(item.passSecond)
                  }`
                }}</i>
						<i class="show-name default-desc" v-if="item.showName && item.showName != '未学'">
							{{ item.showName }}</i>
					</div>
					<div class="progress" v-if="!isExamLesson(item.contentType)">
						<van-progress style="margin: 12px 0" :percentage="item.studyPercent" stroke-width="2px" />
					</div>
				</div>
				<em class="lesson-status" v-if="isLesson(item.type)" :class="[
            item.studyStatus == 1 ||
            item.studyStatus === null ||
            item.studyStatus === undefined
              ? 'empty'
              : item.studyStatus == 2
              ? 'half'
              : 'full',
            item.chapterStatusLine ? 'line' : ''
          ]"></em>
			</div>
			<div v-if="item.children" class="qy-tree-node_children">
				<div class="qy-tree-node-content" :class="[activeNode(cl.chapterId) ? 'is_current' : '']"
					v-for="(cl, cdx) in item.children" :key="cdx" @click="nodeClick(cl)">
					<div class="content-top">
						<i class="playing"></i>
						<i class="index-name">{{ cl.chapterIndexName }}</i>
						<i class="content-name ellipsis">
							<span>{{ "「" + getCurrentLesson(cl.contentType).name + "」" }}</span>{{ cl.name }}</i>
					</div>
					<div class="content-bottom">
							<div class="flex-wrap flex-column">
								<i class="default-desc" v-show="!isExamLesson(cl.contentType)">{{
                    `需用时：${cl.passSecond == 0 ? "学习即完成 " : getTime(cl.passSecond)}`
                  }}</i>
								<i class="show-name default-desc"
									v-if="item.showName && item.showName != '未学'">{{ cl.showName }}</i>
							</div>
							<div class="progress" v-if="!isExamLesson(cl.contentType)">
								<van-progress style="margin: 12px 0" :percentage="cl.studyPercent" stroke-width="2px" />
							</div>
					</div>

					<em class="lesson-status" :class="[
              cl.studyStatus == 1 ||
              cl.studyStatus === null ||
              cl.studyStatus === undefined
                ? 'empty'
                : cl.studyStatus == 2
                ? 'half'
                : 'full',
              cl.chapterStatusLine ? 'line' : ''
            ]"></em>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import {
		lessonTypes
	} from "@/assets/js/constant";
	import {
		deleteEmptyChildren,
		genSimpleList,
		initOrgTreeData
	} from "@/assets/js/org.js";
	import {
		getTime,
		parse,
		stringify
	} from "@/assets/js/util";
	import VanProgress from "@/components/vant/van-progress/van-progress.vue";
	import mockData from "@/mock/course/chapter.json"
	export default {
		components: {
			VanProgress
		},
		data() {
			return {
				pageLoading: false,
				localChapterIndex: 1,
				localLessonIndex: 1,
				originList: [],
				list: [],
				firstLesson: null, // 默认选中的第一课时
				unStudyList: [], // 未学习列表
				currentChapterId: "",
				isBuy: false, // 是已经购买过课程
			};
		},
		props: {
			courseId: {
				type: String,
				default: ""
			},
			/**
			 * 跳转的课程ID
			 */
			learnChapterId: {
				type: String,
				default: ""
			},
			highlightNode: {
				// 是否高亮节点
				type: Boolean,
				default: false
			},
			initChapterId: {
				// 初始化高点节点的ID（如果想选中第一个，默认为first）
				type: String,
				default: ""
			},
			learnStatus: {
				type: Boolean,
				default: false
			},
			isView: {
				// 是否是预览模式
				type: Boolean,
				default: false
			},
			isStudyFree: {
				// 是否自由学习
				type: Boolean,
				default: true
			},
			disabled: {
				// 是否禁用
				type: Boolean,
				default: false
			},
			courseInfo: {
				// 课程详情信息
				type: Object,
				default: () => {}
			},
			chapterProgressInfo: {
				// 课程最新的进度信息
				type: Object,
				default: () => {}
			},
			currentUpdataTime: {
				type: [String, Number],
				default: ""
			}
		},
		watch: {
			currentUpdataTime() {
				this.getChapterList()
			},
			chapterProgressInfo(val, old) {
				this.list.forEach((item, index) => {
					if (item.chapterId == val.chapterId) {
						this.$set(this.list[index], 'studyPercent', val.studyPercent)
						this.$forceUpdate();
						return
					}
					if (item.children && item.children.length) {
						item.children.forEach((c, indey) => {
							if (c.chapterId == val.chapterId) {
								this.$set(this.list[index].children[indey], 'studyPercent', val
									.studyPercent)
								this.$forceUpdate();
							}
						})
					}
				})
			},
			curserInfo: {
				handler: function(val) {
					if (val) {
						this.isBuy = val.buyStatus === '1';
					} else {
						this.isBuy = true
					}
				},
				immediate: true
			}
		},

		mounted() {
			this.getChapterList()
		},

		methods: {
			isLesson(type) {
				return type === "L";
			},

			isChapter(type) {
				return type === "C";
			},

			isExamLesson(type) {
				return type === "E";
			},

			activeNode(id) {
				return this.currentChapterId === id;
			},

			getTime(s) {
				return getTime(s);
			},

			// 获取当前编辑的课时
			getCurrentLesson(type) {
				let res = {};
				lessonTypes.forEach(item => {
					if (type === item.type) {
						res = item;
					}
				});
				return res;
			},

			getChapterList() {
				let res = mockData;
				this.localChapterIndex = 1;
				this.localLessonIndex = 1;
				this.originList = res.data || res;
				let copy = parse(stringify(res.data || res));
				this.list = deleteEmptyChildren(initOrgTreeData(genSimpleList(copy)));
				this.setTreeTitle(this.list);
				this.getUnStudyList(this.list);
				// 设置高亮节点
				if (this.highlightNode && this.initChapterId) {
					this.$nextTick(() => {
						let key = "";
						if (!this.learnChapterId) {
							if (this.initChapterId === "first") {
								this.getFirstLesson(this.list);
								key = this.firstLesson ? this.firstLesson.chapterId : "";
							} else {
								key =
									this.getChapterByChapterId(this.initChapterId).chapterId ||
									"";
								if (!key) {
									this.getFirstLesson(this.list);
									key = this.firstLesson ? this.firstLesson.chapterId : "";
								}
							}
						} else {
							let navigatorLesson = this.getChapterByChapterId(
								this.learnChapterId
							);
							if (this.isStudyFree) {
								key = navigatorLesson.chapterId || "";
							} else {
								if (
									(this.unStudyList.length > 0 &&
										this.learnChapterId === this.unStudyList[0].chapterId) ||
									(navigatorLesson.studyStatus != 1 &&
										navigatorLesson.studyStatus != 2 &&
										!this.isView)
								) {
									key = navigatorLesson.chapterId || "";
								} else {
									this.$toast.fail(
										"当前课程为非自由学习模式，已为您切换到上次学习的课时"
									);
									if (this.initChapterId === "first") {
										this.getFirstLesson(this.list);
										key = this.firstLesson ? this.firstLesson.chapterId : "";
									} else {
										key =
											this.getChapterByChapterId(this.initChapterId)
											.chapterId || "";
									}
								}
							}
						}
						if (key) {
							this.currentChapterId = key;
							this.$emit("current-data", this.getChapterByChapterId(key));
						}
					});
				}
			},

			// 根据CHAPTERID查询课时
			getChapterByChapterId(chapterId) {
				let chapter = {};
				this.originList.forEach(item => {
					if (item.chapterId === chapterId) {
						chapter = item;
					}
				});
				return chapter;
			},

			// 选中第一课时
			getFirstLesson(list) {
				for (let i in list) {
					let item = list[i];
					if (item.children && item.children.length > 0) {
						this.getFirstLesson(item.children);
					} else {
						if (item.type === "L" && this.firstLesson === null) {
							this.firstLesson = item;
						}
					}
				}
			},

			// 获取未学习列表(自由学习功能使用)
			getUnStudyList(list) {
				for (let i in list) {
					let item = list[i];
					if (item.children && item.children.length > 0) {
						this.getUnStudyList(item.children);
					} else {
						if (
							item.type === "L" &&
							(item.studyStatus == 1 || item.studyStatus == 2)
						) {
							this.unStudyList.push(item);
						}
					}
				}
			},

			// 设置章节目录
			setTreeTitle(list) {
				for (let i in list) {
					let item = list[i];
					if ((item.children && item.children.length > 0) || item.type === "C") {
						item.chapterIndexName = `第${this.localChapterIndex}章`;
						this.localChapterIndex++;
						this.setTreeTitle(item.children);
					} else {
						if (item.parentId && item.parentId != "0") {
							item.chapterIndexName = `第${parseInt(i) + 1}节`;
							// 标记(章节下课时横线样式)
							if (i < list.length - 1) {
								item.chapterStatusLine = true;
							}
						} else {
							// 表示单独的课时
							item.chapterIndexName = `第${this.localLessonIndex}节`;
							this.localLessonIndex++;
						}
					}
				}
			},

			isMediaChapter(type) {
				return type === "V" || type === "A";
			},
			nodeClick(data) {
				if (
					this.isChapter(data.type) ||
					this.currentChapterId === data.chapterId ||
					this.disabled
				)
					return;
				if (this.learnStatus) {
					// 如果不是自由学习(且含有未学习完的章节)
					if (!this.isStudyFree && this.unStudyList.length > 0) {
						let firstUnstudyChapter = this.unStudyList[0];
						if (
							data.chapterId != firstUnstudyChapter.chapterId &&
							(data.studyStatus == 1 || data.studyStatus == 2) &&
							!this.isView
						) {
							// 获取章节信息
							let chapter = null;
							firstUnstudyChapter.parentId &&
								(chapter = this.getChapterById(
									firstUnstudyChapter.parentId,
									this.list
								));
							this.$toast.warning(
								`当前课程为非自由学习模式，请先完成：${
                    chapter ? chapter.chapterIndexName + "-" + chapter.name : ""
                } ${firstUnstudyChapter.chapterIndexName}-${
                    firstUnstudyChapter.name
                }！`
							);
						} else {
							this.currentChapterId = data.chapterId;
							this.$emit("current-data", data);
						}
					} else {
						this.currentChapterId = data.chapterId;
						this.$emit("current-data", data);
					}
				} else {
					if (
						(this.courseInfo.courseConfig &&
							this.courseInfo.courseConfig.isSignin == "1" &&
							this.courseInfo.isSigned == "1") ||
						this.courseInfo.courseConfig.isSignin == 2
					) {
						this.goLearnPage(data);
					} else {
						this.$toast.warning("请先签到");
						return false;
					}
				}
			},

			// 自动播放下一音视频课时
			playNextMediaChapter(chapterId, play = false) {
				let nextChapter = this.getNextChapterdByCurrentChapterId(chapterId);

				if (
					nextChapter &&
					(nextChapter.contentType === "V" || nextChapter.contentType === "A")
				) {
					let key = nextChapter.id;
					this.currentChapterId = nextChapter.chapterId;
					this.$emit("current-data", nextChapter, true, play);
				}
			},

			// 根据当前课时查找下一课时
			getNextChapterdByCurrentChapterId(id) {
				let chapterTempList = [];
				this.originList.forEach(item => {
					if (item.type === "L") {
						chapterTempList.push(item);
					}
				});
				let index = chapterTempList.findIndex(item => item.chapterId === id);
				if (index === chapterTempList.length - 1) {
					return null;
				} else {
					return chapterTempList[index + 1];
				}
			},

			// 跳转至学习页
			goLearnPage(data) {
				if (this.isLesson(data.type)) {
					// 跳转学习页 跳转之前需要更新studyLogId
					uni.removeStorageSync("studyLogId");
					this.$uniPush({
						name: "course-learn-id-chapter",
						params: {
							id: data.courseId,
							chapter: data.chapterId
						}
					});
				}
			}
		}
	};
</script>

<style lang="scss" scoped>
	@import "@/static/css/variable.scss";

	.qy-com-course-lesson {
		.qy-tree-node {
			font-size: 14px;

			.qy-tree-node-content {
				padding: 14px 15px 24px;
				padding-left: 35px;
				// border-bottom: 1px solid #ddd;
				position: relative;

				.content-top {
					height: 20px;
				}

				.content-bottom {
					margin-top: 6px;
					height: 16px;
					display: flex;
					justify-content: space-between;
				}

				.playing {
					display: none;
				}

				&.is_current {
					.playing {
						display: none;
						// display: inline-block;
						width: 8px;
						height: 8px;
						background-image: url("../../static/image/icon_course_playing.png");
						background-size: 100% 100%;
						position: absolute;
						left: 20px;
						top: 20px;
					}

					.index-name,
					.content-name {
						color: $primaryColor;
					}
				}

				.index-name {
					margin-right: 10px;
				}

				.content-name {
					display: inline-block;
					max-width: 80%;
					vertical-align: bottom;
				}

				.show-name {
					/* position: absolute;
                  right: 15px; */
				}

				.progress {
					margin-top: 2px;
					width: 30%;
					padding-right: 5px;
				}

				.progress_1 {
					margin-top: 2px;
					width: 80%;
					padding-right: 5px;
				}

				&:last-child {
					border: 0;

					&:after {
						display: none;
					}
				}
			}

			.qy-tree-node_parent {
				background: #f6f6f6;
				border: 0;
				font-weight: bold;
				padding-left: 15px;
				padding-bottom: 14px;
			}

			.qy-tree-node_children {
				.qy-tree-node-content {
					&:after {
						content: " ";
						width: calc(100% - 45px);
						height: 1px;
						background: #d8d8d8;
						position: absolute;
						bottom: 0;
					}
				}
			}

			.lesson-status {
				@include lessonStatus;
			}
		}
	}
</style>